<template>
    <div class="virtual-table-container" ref="container">
      <el-table
        :data="visibleData"
        :row-key="rowKey"
        border
        ref="table"
        v-bind="$attrs"
        v-on="$listeners"
        :max-height="containerHeight"
        @header-dragend="handleResize"
      >
        <slot name="header"></slot>
      </el-table>
      <div
        class="virtual-scroll-bar"
        :style="{ height: containerHeight + 'px' }"
        @scroll.passive="handleScroll"
        ref="scrollBar"
      >
        <div :style="{ height: totalHeight + 'px' }"></div>
      </div>
    </div>
  </template>
  
  <script>
  export default {
    name: 'VirtualScrollTable',
    props: {
      data: {
        type: Array,
        required: true
      },
      rowHeight: {
        type: Number,
        default: 48 // 默认行高，根据实际样式调整
      },
      buffer: {
        type: Number,
        default: 10 // 上下缓冲行数
      },
      rowKey: {
        type: String,
        default: 'id'
      },
      height: {
        type: [String, Number],
        default: '100%'
      }
    },
    data() {
      return {
        startIndex: 0,
        containerHeight: 0,
        isInitialized: false,
        headerHeight: 40 // 默认表头高度
      }
    },
    computed: {
      totalHeight() {
        return this.data.length * this.rowHeight
      },
      visibleCount() {
        return Math.ceil(this.containerHeight / this.rowHeight) + this.buffer * 2
      },
      visibleData() {
        const start = Math.max(0, this.startIndex - this.buffer)
        const end = Math.min(this.data.length, start + this.visibleCount)
        return this.data.slice(start, end)
      }
    },
    mounted() {
      this.initTable()
      window.addEventListener('resize', this.handleResize)
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.handleResize)
    },
    watch: {
      data() {
        this.$nextTick(() => {
          this.updateTotalHeight()
          this.initTable()
        })
      },
      visibleData() {
        this.$nextTick(() => {
          if (this.$refs.table) {
            this.$refs.table.doLayout()
          }
        })
      },
      height() {
        this.$nextTick(() => {
          this.initTable()
        })
      }
    },
    methods: {
      initTable() {
        this.$nextTick(() => {
          // 设置容器高度
          const container = this.$refs.container
          if (typeof this.height === 'number') {
            container.style.height = `${this.height}px`
            this.containerHeight = this.height
          } else if (this.height === '100%') {
            container.style.height = '100%'
            this.containerHeight = container.clientHeight
          } else {
            container.style.height = this.height
            this.containerHeight = container.clientHeight
          }

          // 获取实际表头高度
          if (this.$refs.table) {
            const headerWrapper = this.$refs.table.$el.querySelector('.el-table__header-wrapper')
            if (headerWrapper) {
              this.headerHeight = headerWrapper.offsetHeight
              // 动态调整滚动条的顶部边距
              if (this.$refs.scrollBar) {
                this.$refs.scrollBar.style.marginTop = `${this.headerHeight}px`
              }
            }
          }

          // 初始化滚动条
          this.updateScrollBar()
          
          // 绑定表格原生滚动事件，同步虚拟滚动条
          if (!this.isInitialized && this.$refs.table) {
            const bodyWrapper = this.$refs.table.$el.querySelector('.el-table__body-wrapper')
            if (bodyWrapper) {
              bodyWrapper.addEventListener('scroll', this.syncScrollBar)
              this.isInitialized = true
            }
          }
        })
      },
      updateTotalHeight() {
        // 更新总高度
        if (this.$refs.scrollBar && this.data.length > 0) {
          const scrollContent = this.$refs.scrollBar.firstElementChild
          if (scrollContent) {
            scrollContent.style.height = `${this.totalHeight}px`
          }
        }
      },
      handleResize() {
        this.$nextTick(() => {
          this.initTable()
        })
      },
      handleScroll(e) {
        const scrollTop = e.target.scrollTop
        this.startIndex = Math.floor(scrollTop / this.rowHeight)
        
        // 同步表格滚动位置
        if (this.$refs.table) {
          const bodyWrapper = this.$refs.table.$el.querySelector('.el-table__body-wrapper')
          if (bodyWrapper && Math.abs(bodyWrapper.scrollTop - scrollTop) > 5) {
            bodyWrapper.scrollTop = scrollTop
          }
        }
      },
      syncScrollBar(e) {
        // 当表格滚动时，同步虚拟滚动条
        if (this.$refs.scrollBar && e.target) {
          const scrollTop = e.target.scrollTop
          if (Math.abs(this.$refs.scrollBar.scrollTop - scrollTop) > 5) {
            this.$refs.scrollBar.scrollTop = scrollTop
            this.startIndex = Math.floor(scrollTop / this.rowHeight)
          }
        }
      },
      updateScrollBar() {
        // 更新滚动条宽度，确保与表格一致
        if (this.$refs.table && this.$refs.scrollBar) {
          const tableWidth = this.$refs.table.$el.offsetWidth
          this.$refs.scrollBar.style.width = `${tableWidth}px`
          this.updateTotalHeight()
        }
      },
      // 暴露el-table的常用方法
      clearSelection() {
        this.$refs.table.clearSelection()
      },
      toggleRowSelection(row, selected) {
        this.$refs.table.toggleRowSelection(row, selected)
      },
      toggleRowExpansion(row, expanded) {
        this.$refs.table.toggleRowExpansion(row, expanded)
      },
      setCurrentRow(row) {
        this.$refs.table.setCurrentRow(row)
      },
    }
  }
  </script>
  
  <style scoped>
  .virtual-table-container {
    width: 100%;
    position: relative;
    overflow: hidden;
  }
  
  .virtual-scroll-bar {
    position: absolute;
    top: 0;
    right: 0;
    width: 17px; /* 标准滚动条宽度 */
    overflow-y: auto;
    overflow-x: hidden;
    z-index: 1;
    opacity: 1; /* 改为完全可见 */
    pointer-events: auto;
    /* 避开表头区域，不干扰表头拖拽 */
    margin-top: 40px; /* 预留表头高度，避免干扰表头拖拽 */
  }
  
  /* 自定义滚动条样式 */
  .virtual-scroll-bar::-webkit-scrollbar {
    width: 8px;
  }
  
  .virtual-scroll-bar::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
  }
  
  .virtual-scroll-bar::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
  }
  
  .virtual-scroll-bar::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
  }
  
  /* 隐藏表格自带的滚动条 */
  ::v-deep .el-table__body-wrapper::-webkit-scrollbar {
    width: 0;
    display: none;
  }
  
  ::v-deep .el-table__body-wrapper {
    scrollbar-width: none;
    -ms-overflow-style: none;
  }
  
  /* 确保表头区域可以正常拖拽 */
  ::v-deep .el-table__header-wrapper {
    z-index: 2; /* 确保表头在滚动条之上 */
  }
  
  /* 确保列拖拽区域正常工作 */
  ::v-deep .el-table__column-resize-proxy {
    z-index: 10; /* 确保拖拽指示器在最上层 */
  }
  </style>